package com.weiaibenpao.demo.chislim.ui.activity.running;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.PolylineOptions;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.lib.WheelView;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.TwoPointLine;
import com.weiaibenpao.demo.chislim.base.BaseActivity;
import com.weiaibenpao.demo.chislim.bean.DistrictBean;
import com.weiaibenpao.demo.chislim.bean.ProvinceBean;
import com.weiaibenpao.demo.chislim.bean.UserSportsInfoBean;
import com.weiaibenpao.demo.chislim.db.preferences.UserPreferences;
import com.weiaibenpao.demo.chislim.presenter.NormalRunFPresenter;
import com.weiaibenpao.demo.chislim.ui.widget.CustomTitleBar;
import com.weiaibenpao.demo.chislim.utils.Constant;
import com.weiaibenpao.demo.chislim.utils.JsonProvinceUtils;
import com.weiaibenpao.demo.chislim.utils.PolyLinesUtils;
import com.weiaibenpao.demo.chislim.utils.Utils;
import com.weiaibenpao.demo.chislim.view.NormalRunFView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class RegionActivity extends BaseActivity<NormalRunFView, NormalRunFPresenter> implements NormalRunFView {
    private final int POLYLINE_OVER_SUCCESS = 1010;
    @BindView(R.id.text_region_distance)
    TextView textRegionDistance;
    @BindView(R.id.text_district)
    TextView textDistrict;
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.map_layout)
    RelativeLayout mapLayout;
    @BindView(R.id.region_bar)
    CustomTitleBar customTitleBar;
    private AMap map;
    private OptionsPickerView pvOptions;
    private ArrayList<ProvinceBean> options1Items;
    private ArrayList<ArrayList<String>> options2Items;
    private ArrayList<ArrayList<ArrayList<String>>> options3Items;
    private JsonProvinceUtils jsonProvinceUtils;
    private int num1, num2, num3;
    private PolyLinesUtils polylineUtil;
    private String province;
    private String code;
    private int pointNum;
    private double runDistance;
    private Bitmap viewToBitmap;
    private double perimeter = 0;
    private String cityName;
    private String districtName;
    private String location;
    private int runColor;
    private List<TwoPointLine> twoPointLines;
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case POLYLINE_OVER_SUCCESS:
                    polylineUtil.setColor(0);
                    twoPointLines = (List<TwoPointLine>) msg.obj;
                    if (twoPointLines != null && twoPointLines.size() > 0) {
                        pointNum = twoPointLines.size();
                        if (runDistance > 0 && runDistance < perimeter) {
                            drawLine();
                        }
                    }
                    break;

            }
        }
    };
    private UserPreferences preferences;
    private int userId;

    public static void openActivity(Context context, String code, String provinceName, double runDistance, double perimeter) {
        Intent intent = new Intent(context, RegionActivity.class);
        intent.putExtra(Constant.CITY_CODE, code);
        intent.putExtra(Constant.PROVINCE, provinceName);
        intent.putExtra(Constant.RUN_DISTANCE, runDistance);
        intent.putExtra(Constant.DISTRICT_DISTANCE, perimeter);
        context.startActivity(intent);
    }


    @Override
    public int setLayoutResourceID() {
        return R.layout.activity_region;
    }

    @Override
    public NormalRunFPresenter initPresenter() {
        return new NormalRunFPresenter();
    }

    /**
     * 选择不同的城市，如果已经有跑步里程，画图
     */
    private void drawLine() {
        int currentNum = (int) (pointNum * (runDistance / perimeter));
        for (int i = 0; i < currentNum; i++) {
            PolylineOptions options = new PolylineOptions();
            options.width(12).color(getResources().getColor(R.color.color_run)).zIndex(200);
            options.addAll(twoPointLines.get(i).getLatLngs());
            map.addPolyline(options);

        }
    }

    private void initData() {
        jsonProvinceUtils = new JsonProvinceUtils(this);
        jsonProvinceUtils.initJsonData();
        options1Items = jsonProvinceUtils.getOptions1Items();
        options2Items = jsonProvinceUtils.getOptions2Items();
        options3Items = jsonProvinceUtils.getOptions3Items();
    }

    @Override
    public void init(Bundle savedInstanceState) {
        preferences = UserPreferences.getInstance();
        userId = preferences.getInt(UserPreferences.USER_ID);
        province = getIntent().getStringExtra(Constant.PROVINCE);
        code = getIntent().getStringExtra(Constant.CITY_CODE);
        perimeter = getIntent().getDoubleExtra(Constant.DISTRICT_DISTANCE, 0);
        runDistance = getIntent().getDoubleExtra(Constant.RUN_DISTANCE, 0);
        mapView.onCreate(savedInstanceState);
        textDistrict.setText(province);
        textRegionDistance.setText(Utils.decimalFormat(perimeter));

        initMap();

        initData();
    }

    private void initMap() {
        if (map == null) {
            map = mapView.getMap();
        }
        map.getUiSettings().setZoomControlsEnabled(false);
        map.getUiSettings().setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);//设置logo位置
//        map.getUiSettings().setZoomGesturesEnabled(false);//禁用或启用缩放手势
//        map.getUiSettings().setScrollGesturesEnabled(false);//禁用或开启平移（滑动）手势
        runColor = getResources().getColor(R.color.color_run);
        polylineUtil = new PolyLinesUtils(this, map);
        initPolyLine();

    }

    /**
     * 初始化PolyLinesUtils得一些信息
     */
    private void initPolyLine() {

        if (runDistance >= perimeter) {
            polylineUtil.setColor(runColor);
        } else
            polylineUtil.setColor(0);
        polylineUtil.drawLine(code + "", mHandler);

    }

    @OnClick({R.id.layout_regions_more, R.id.right_text, R.id.left_image})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.right_text:
                if (!TextUtils.isEmpty(location) && !TextUtils.isEmpty(code))
                    EventBus.getDefault().post(new DistrictBean(location, code, perimeter, runDistance, gradeName));
                finish();
                break;
            case R.id.layout_regions_more:
                showPickerView();
                break;
            case R.id.left_image:
                finish();
                break;
        }
    }

    /**
     * 显示 城市列表
     */
    private void showPickerView() {
        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {

                num1 = options1;
                num2 = options2;
                num3 = options3;
                province = options1Items.get(options1).getPickerViewText();
                cityName = options2Items.get(options1).get(options2);
                districtName = options3Items.get(options1).get(options2).get(options3);
                ProvinceBean provinceBean = options1Items.get(options1);
                if (cityName.equals("全部")) {
                    location = province;

                    perimeter = Float.parseFloat(options1Items.get(options1).getProvincePerimeter());
                    code = provinceBean.getProvinceCode();

                } else if (districtName.equals("全部")) {
                    ProvinceBean.CitylistBean citylistBean = provinceBean.getCitylist().get(options2);
                    location = province + cityName;
                    perimeter = Float.parseFloat(citylistBean.getCityPerimeter());
                    code = citylistBean.getCityCode();

                } else {
                    ProvinceBean.AreaListBean areaListBean = options1Items.get(options1).getCitylist().get(options2).getAreaList().get(options3);
                    location = province + cityName + districtName;
                    perimeter = Float.parseFloat(areaListBean.getAreaPerimeter());
                    code = areaListBean.getAreaCode();
                }
                mPresenter.getUserSportsInfo(userId, 23, code);
                initPolyLine();

                if (!TextUtils.isEmpty(location)) textDistrict.setText(location);
                if (!TextUtils.isEmpty(Utils.decimalFormat(perimeter)))
                    textRegionDistance.setText(Utils.decimalFormat(perimeter));
            }
        }).setTitleText(" ")
                .setDividerColor(Color.BLACK)
                .setOutSideCancelable(true)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setSubmitColor(Color.parseColor("#333333"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#333333"))//取消按钮文字颜色
                .setLineSpacingMultiplier(3.0f)
                .setSelectOptions(num1, num2, num3)
                .setDividerType(WheelView.DividerType.FILL)
                .setDividerColor(Color.parseColor("#FFFFFF"))
                .setTitleBgColor(Color.parseColor("#FFFFFF"))
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        mapView.onDestroy();
        super.onDestroy();


    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        mapView.onSaveInstanceState(outState);
    }

    private String gradeName="暂无排名";

    @Override
    public void requestSuccess(UserSportsInfoBean userSportsInfoBean) {
        if (userSportsInfoBean.getRankNumber() == null) {
            gradeName = "暂无排名";
        } else {
            gradeName = userSportsInfoBean.getRankNumber().getRownum() == 0 ? "暂无排名" : "第" + userSportsInfoBean.getRankNumber().getRownum() + "名";
        }
        runDistance = userSportsInfoBean.getDjqSumSportsResult().getFinishDistance();
        initPolyLine();
    }
}
